package com.weiya.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weiya.entity.Permission;
import com.weiya.entity.Role;
import com.weiya.entity.User;
import com.weiya.model.PermissionTreeListVo;
import com.weiya.response.*;
import com.weiya.service.PermissionService;
import com.weiya.service.RoleService;
import com.weiya.system.shiro.SystemUserRealm;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p class="detail">
 * 功能:角色管理
 * </p>
 *
 * @author BaoWeiwei
 * @ClassName Role controller.
 * @Version V1.0.
 * @date 2018.07.24 13:25:52
 */
@Controller
@RequestMapping("/role")
public class RoleController {

    private static Logger logger = LoggerFactory.getLogger(RoleController.class);
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private SystemUserRealm userRealm;


    /**
     * <p class="detail">
     * 功能:获取角色数据
     * </p>
     *
     * @param role   :
     * @param limit  :
     * @param offset :
     * @return page result vo
     * @author BaoWeiwei
     * @date 2018.07.24 13:46:51
     */
    @PostMapping("/list")
    @ResponseBody
    public PageResultVo loadRoles(Role role, Integer limit, Integer offset) {
        try {
            PageHelper.startPage(PageUtil.getPageNo(limit, offset),offset);
            List<Role> roleList = roleService.selectRoles(role);
            PageInfo<Role> pages = new PageInfo<>(roleList);
            return ResponseUtil.table(roleList,pages.getTotal());
        } catch (Exception e) {
            logger.error(String.format("RoleController.loadRoles%s", e));
            throw e;
        }

    }

    /**
     * <p class="detail">
     * 功能:新增角色
     * </p>
     *
     * @param role :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 14:09:59
     */
    @PostMapping("/add")
    @ResponseBody
    public ResponseVo addRole(Role role) {
        try {
            int a = roleService.insert(role);
            if (a > 0) {
                return ResponseUtil.success("添加角色成功");
            } else {
                return ResponseUtil.error("添加角色失败");
            }
        } catch (Exception e) {
            logger.error(String.format("RoleController.addRole%s", e));
            throw e;
        }
    }


    /**
     * <p class="detail">
     * 功能:查询角色信息
     * </p>
     *
     * @param model  :
     * @param roleId :
     * @return string
     * @author BaoWeiwei
     * @date 2018.07.24 15:36:39
     */
    @GetMapping("/edit/{roleId}")
    public String detail(Model model, @PathVariable("roleId") String roleId) {
        Role role = roleService.findById(roleId);
        model.addAttribute("role", role);
        return "role/detail";
    }

    /**
     * <p class="detail">
     * 功能:修改角色信息
     * </p>
     *
     * @param role :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 15:37:23
     */
    @PostMapping("/edit")
    @ResponseBody
    public ResponseVo editRole(Role role) {
        int a = roleService.updateRole(role);
        if (a > 0) {
            return ResponseUtil.success("修改角色信息成功！");
        } else {
            return ResponseUtil.error("修改角色信息失败！");
        }
    }

    /**
     * <p class="detail">
     * 功能:删除角色
     * </p>
     *
     * @param roleId :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 16:06:05
     */
    @GetMapping("/delete")
    @ResponseBody
    public ResponseVo deleteRole(String roleId) {
        List<String> roleIdsList = Arrays.asList(roleId);
        int a = roleService.updateStatusBatch(roleIdsList, SystemConst.DATA_DELETED);
        if (a > 0) {
            return ResponseUtil.success("删除角色成功");
        } else {
            return ResponseUtil.error("删除角色失败");
        }
    }

    /**
     * <p class="detail">
     * 功能:批量删除角色
     * </p>
     *
     * @param roleIdStr :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 16:18:14
     */
    @GetMapping("/batch/delete")
    @ResponseBody
    public ResponseVo batchDeleteRole(String roleIdStr) {
        String[] roleIds = roleIdStr.split(",");
        List<String> roleIdsList = Arrays.asList(roleIds);
        int a = roleService.updateStatusBatch(roleIdsList,SystemConst.DATA_DELETED);
        if (a > 0) {
            return ResponseUtil.success("删除角色成功");
        } else {
            return ResponseUtil.error("删除角色失败");
        }
    }

    /**
     * <p class="detail">
     * 功能:初始化角色权限
     * </p>
     *
     * @param roleId :
     * @return list
     * @author BaoWeiwei
     * @date 2018.07.24 16:50:38
     */
    @PostMapping("/assign/permission/list")
    @ResponseBody
    public List<PermissionTreeListVo> assignRole(String roleId){
        List<PermissionTreeListVo> listVos = new ArrayList<>();
        // 1、查询所有有效权限
        List<Permission> allPermissions = permissionService.selectAll(SystemConst.DATA_VALID);
        // 2、查询当前角色拥有权限
        List<Permission> hasPermissions = roleService.findPermissionsByRoleId(roleId);
        // 3、选中操作，返回前台
        for(Permission permission : allPermissions){
            PermissionTreeListVo vo = new PermissionTreeListVo();
            vo.setPermissionId(permission.getPermissionId());
            vo.setName(permission.getName());
            vo.setParentId(permission.getParentId());
            for(Permission hasPermission:hasPermissions){
                //有权限则选中
                if(hasPermission.getPermissionId().equals(permission.getPermissionId())){
                    vo.setChecked(true);
                    break;
                }
            }
            listVos.add(vo);
        }
        return listVos;
    }

    /**
     * <p class="detail">
     * 功能:分配权限
     * </p>
     *
     * @param roleId          :
     * @param permissionIdStr :
     * @return response vo
     * @author BaoWeiwei
     * @date 2018.07.24 16:50:34
     */
    @PostMapping("/assign/permission")
    @ResponseBody
    public ResponseVo assignRole(String roleId, String permissionIdStr){
        List<String> permissionIdsList = new ArrayList<>();
        if(StringUtils.isNotBlank(permissionIdStr)){
            String[] permissionIds = permissionIdStr.split(",");
            permissionIdsList = Arrays.asList(permissionIds);
        }
        ResponseVo responseVo = roleService.addAssignPermission(roleId,permissionIdsList);
        // 重新加载角色下所有用户权限
        List<User> userList = roleService.findByRoleId(roleId);
        if(userList.size()>0){
            List<String> userIds = new ArrayList<>();
            for(User user : userList){
                userIds.add(user.getUserId());
            }
            userRealm.clearAuthorizationByUserId(userIds);
        }
        return responseVo;
    }
}
